import axios from 'axios'
import md5 from 'js-md5'
import { Toast } from 'vant'
import CryptoJS from 'crypto-js'
import global from '@/utils/global'
const service = axios.create({
    timeout: 50000 // 设置请求超时
})
// post请求头
service.defaults.baseURL = api_url
service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

const version = '1.0.1'
const device = 'web'
// const device = 'api'
const signKey = focus[47]
const encrypt = 2
// let token = 'fba028c6-13782bc0-33794632-a813-e42eb067f26d'
let token = ''
// 请求拦截器
service.interceptors.request.use(
    async (request) => {
        if (global.isInApp()) {
        token = await global.getToken()
        }
        token = 'c47be86e-1a9c18e8-01544171-8148-fafa409bbc9c'
        const xid = global.getUrlName('xid')
        const time = Date.parse(new Date()) / 1000
        const custom = Math.random().toString(36).substr(2)
        const c = request.url
        let url = ''
        if (c.search('&') !== -1) {
            url = c.substring(0, c.indexOf('&'))
        } else {
            url = c
        }
        let str = xid + signKey + url.toLowerCase() + time + device + version + token + custom
        let sign = md5(str)
        request.headers.xid = xid
        request.headers.version = version
        request.headers.device = device
        request.headers.token = token
        request.headers.encrypt = encrypt
        request.headers.custom = custom
        request.headers.sign = sign
        request.headers.time = time
        return request
    },
    error => {
        return Promise.error(error)
    }
)
// 响应拦截器
service.interceptors.response.use(
    response => {
        Toast.clear()
        const ret = response.data
        const iv = CryptoJS.enc.Hex.parse(md5('key_' + ret.time))
        const option = { iv: iv, padding: CryptoJS.pad.ZeroPadding }
        if (ret.encrypt === 1 && ret.data) {
            let newKey = md5(ret.sign)
            let key = CryptoJS.enc.Hex.parse(newKey)
            let decrypted = CryptoJS.AES.decrypt(ret.data, key, option)
            let string = decrypted.toString(CryptoJS.enc.Utf8)
            try {
                ret.data = JSON.parse(string)
            } catch (e) {
                ret.data = string
            }
        }
        if (ret.code == 401) {
            // token失效，重新登录
            return global.closePage()
        }
        return ret
    },
    error => {
        Toast.clear()
        console.log(error)
    }
)

export default service
